
#import "NoMoneyListViewController.h"
#import "UMMobClick/MobClick.h"
#import "FirstTableViewController.h"

@interface NoMoneyListViewController ()<UIWebViewDelegate,UIScrollViewDelegate, NJKWebViewProgressDelegate>
@property (strong, nonatomic) IBOutlet UIWebView *myWebView;
@property (strong, nonatomic) NJKWebViewProgressView* webViewProgressView;
@property (strong, nonatomic) NJKWebViewProgress* webViewProgress;
//创建一个对象
@property (strong, nonatomic) TRJSExport* jsExport;
@property (strong, nonatomic) ShareView* shareView;
@property (strong, nonatomic) TRJSExport* test;
//返回按钮
@property (nonatomic, strong) UIBarButtonItem *backItem;
//关闭按钮
@property (nonatomic, strong) UIBarButtonItem *closeItem;

//标记是个人签名页面的值；
@property (nonatomic, unsafe_unretained) NSInteger shareIndex;

@end

@implementation NoMoneyListViewController

- (ShareView*)shareView
{
    if (!_shareView)
    {
        _shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:self.shareIndex];
    }
    return _shareView;
}

- (UIBarButtonItem *)closeItem
{
    if (!_closeItem)
    {
        _closeItem = [[UIBarButtonItem alloc] initWithTitle:@"关闭" style:UIBarButtonItemStylePlain target:self action:@selector(closeNative)];
    }
    return _closeItem;
}

- (UIBarButtonItem *)backItem
{
    if (!_backItem) {
        _backItem = [[UIBarButtonItem alloc] init];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *image = LoadImage(@"back1");
        [btn setImage:image forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(backNative) forControlEvents:UIControlEventTouchUpInside];
        //字体的多少为btn的大小
        [btn sizeToFit];
        //左对齐
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        //让返回按钮内容继续向左边偏移15，如果不设置的话，就会发现返回按钮离屏幕的左边的距离有点儿大，不美观
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        btn.frame = CGRectMake(0, 0, 40, 40);
        _backItem.customView = btn;
    }
    return _backItem;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.shareIndex = 1;
//    self.title = @"0元赠险";
    self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
    UIScrollView *tempView = (UIScrollView *)[self.myWebView.subviews objectAtIndex:0];
    tempView.showsVerticalScrollIndicator = NO;
    tempView.showsHorizontalScrollIndicator = NO;
    tempView.delegate = self;
    //设置不弹性
    tempView.bounces = NO;
    [self showProgressView];
}

//加载链接
- (void)loadURl
{
    NSLog(@"0元赠险 url ＝ %@",[NSString stringWithFormat:@"%@agentId=%@&app=1&isHideNavi=1",HTML_URL,[TRUserAgenCode getCustomerId]]);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@agentId=%@&app=1&isHideNavi=1",HTML_URL,[TRUserAgenCode getCustomerId]]]];
    [self.myWebView loadRequest:request];
}

//创建进度条
- (void)showProgressView
{
    self.webViewProgress = [[NJKWebViewProgress alloc] init];
    self.myWebView.delegate = self.webViewProgress;
    self.webViewProgress.webViewProxyDelegate = self;
    self.webViewProgress.progressDelegate = self;
    
    
    CGRect navBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0,
                                 navBounds.size.height - 3,
                                 navBounds.size.width,
                                 3);
    self.webViewProgressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    self.webViewProgressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.webViewProgressView setProgress:0 animated:YES];
    [self loadURl];
    [self.navigationController.navigationBar addSubview:self.webViewProgressView];
}

#pragma mark - NJKWebViewProgressDelegate
- (void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    [self.webViewProgressView setProgress:progress animated:YES];
    self.title = [self.myWebView stringByEvaluatingJavaScriptFromString:@"document.title"];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"NoMoneyListViewController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.webViewProgressView removeSubviews];
    [MobClick endLogPageView:@"NoMoneyListViewController"];
}

//判断并且登录
- (void)judeLoginWithMessage:(NSString*)message
{
    ShowLogin(self.navigationController);
}

//外链分享
- (void)share
{
    NSString* selfURL = [NSString stringWithFormat:@"%@agentId=%@&app=1&isHideNavi=1",HTML_URL,[TRUserAgenCode getCustomerId]];
//    NSLog(@"0远赠险 url = %@",selfURL);
    if ([TRUserAgenCode isLogin])
    {
        self.shareView.message = [NSString stringWithFormat:@"%@!#%@!#%@!#%@",@"真话保险",@"fre_get1.png",@"免费领取",selfURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:self.shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
        });
    }
    else
    {
        [self judeLoginWithMessage:@"您还没登录，请先登录!"];
    }
}

- (void)backNative
{
    //判断是否有上一层H5页面
    if ([self.myWebView canGoBack])
    {
        //如果有则返回
        [self.myWebView goBack];
        //同时设置返回按钮和关闭按钮为导航栏左边的按钮
        self.navigationItem.leftBarButtonItems = @[self.backItem, self.closeItem];
    }
    else
    {
        [self closeNative];
    }
}

//关闭H5页面，直接回到原生页面
- (void)closeNative
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mark - web视图完成调用后执行（代理方法）

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
}

- (void)hidenButtonWithStr:(NSString*)str
{
    if (str && str.length == 2)
    {
        NSString * str1 = [str substringToIndex:1];
        NSString * str2 = [str substringFromIndex:1];
        NSLog(@"str1 = %@, str2 = %@",str1,str2);
        if ([str1 isEqualToString:@"1"] && [str2 isEqualToString:@"1"])
        {
            //隐藏返回按钮
            [self.navigationItem setHidesBackButton:YES];
            self.navigationItem.leftBarButtonItems = @[];
        }
        else if ([str1 isEqualToString:@"1"] && ![str2 isEqualToString:@"1"])
        {
            self.navigationItem.leftBarButtonItems = @[self.closeItem];
        }
        else if (![str1 isEqualToString:@"1"] && [str2 isEqualToString:@"1"])
        {
            self.navigationItem.leftBarButtonItems = @[self.backItem];
        }
        else
        {
            self.navigationItem.leftBarButtonItems = @[self.backItem,self.closeItem];
        }
    }
    
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.test = [[TRJSExport alloc]init];
    [self.test returnBoolForJS:^(NSInteger isBack) {
        [self cleanCacheAndCookie];
        //            [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.test postMessageForJS:^{
        NSLog(@"h5调用原生方法是否安装微信");
    }];
    
    //是否隐藏‘分享’按钮
    [self.test returnhideShareButtonForJS:^(NSString *message) {
        NSLog(@"h5返回来的是否隐藏导航了分享按钮的值");
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([message isEqualToString:@"1"])
            {
                self.navigationItem.rightBarButtonItem = nil;
            }
            else
            {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
            }
        });
    }];
    
    [self.test returnBackBtnClosed:^(NSString *message) {
        NSLog(@"h5返回来的是否关闭“关闭'按钮的值：%@",message);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hidenButtonWithStr:message];
        });
    }];
    
    [self.test returnCloseBtnClosed:^(NSString *message) {
        
    }];
    
    [self.test returnJudgSignPageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    
    [self.test returnMessageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    context[@"testobject"] = self.test;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //首先创建JSContext 对象（此处通过当前webView的键获取到jscontext）
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    self.test = [[TRJSExport alloc]init];
    [self.test returnBoolForJS:^(NSInteger isBack) {
        [self cleanCacheAndCookie];
        //            [self dismissViewControllerAnimated:YES completion:nil];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [self.test postMessageForJS:^{
        NSLog(@"h5调用原生方法是否安装微信");
    }];
    
    //是否隐藏‘分享’按钮
    [self.test returnhideShareButtonForJS:^(NSString *message) {
        NSLog(@"h5返回来的是否隐藏导航了分享按钮的值");
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([message isEqualToString:@"1"])
            {
                self.navigationItem.rightBarButtonItem = nil;
            }
            else
            {
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"分享" style:UIBarButtonItemStylePlain target:self action:@selector(share)];
            }
        });
    }];
    
    [self.test returnBackBtnClosed:^(NSString *message) {
        NSLog(@"h5返回来的是否关闭“关闭'按钮的值：%@",message);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hidenButtonWithStr:message];
        });
    }];
    
    [self.test returnCloseBtnClosed:^(NSString *message) {
        
    }];
    
    [self.test returnJudgSignPageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    
    [self.test returnMessageForJS:^(NSString *message) {
        NSLog(@"分享message = %@",message);
        ShareView* shareView = [[ShareView alloc]initWithFrame:CGRectMake(0, UISCREENHEIGHT - 125, UISCREENWEITH, 125) withIndex:0];
        shareView.message = message;
        dispatch_async(dispatch_get_main_queue(), ^{
            [[UIApplication sharedApplication].keyWindow addSubview:shareView.backView];
            [[UIApplication sharedApplication].keyWindow addSubview:shareView];
        });
    }];
    context[@"testobject"] = self.test;
}

- (void)viewDidDisappear:(BOOL)animated
{
    //清除UIWebView的缓存
    [self cleanCacheAndCookie];
}

- (void)dealloc
{
    //清除UIWebView的缓存
    [self cleanCacheAndCookie];
}

/**清除缓存和cookie*/
- (void)cleanCacheAndCookie
{
    //清除cookies
    NSLog(@"---------清除cookies");
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}


@end
